/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rpinfo.editalog.importalog;

import com.rpinfo.editalog.util.DaoFactory;
import com.rpinfo.editalog.util.Util;
import com.rpinfo.editalog.venda.Fin;
import com.rpinfo.editalog.venda.FinDaoHibernate;
import com.rpinfo.editalog.venda.FinTableModel;
import com.rpinfo.editalog.venda.VitTableModel;
import com.rpinfo.editalog.venda.Vit;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.util.converter.DateTimeStringConverter;
import javax.swing.JOptionPane;

/**
 *
 * @author camilo
 */
public class ImportaLogJDialog extends javax.swing.JDialog {

  FinTableModel finTableModel = new FinTableModel();
  VitTableModel vitTableModel = new VitTableModel();
  Fin fin = new Fin();
  List<Fin> lstfin = new ArrayList<>();
  List<Vit> lstvit = new ArrayList<>();

  /**
   * Creates new form JDialogProcessaLog
   *
   * @param parent
   * @param modal
   */
  public ImportaLogJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();

  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jPanel3 = new javax.swing.JPanel();
    jTabbedPane1 = new javax.swing.JTabbedPane();
    jPanel1 = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtFin = new javax.swing.JTable();
    jPanel2 = new javax.swing.JPanel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jtVit = new javax.swing.JTable();
    jPanel4 = new javax.swing.JPanel();
    jpBotoes = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

    jtFin.setAutoCreateRowSorter(true);
    jtFin.setModel(finTableModel);
    jtFin.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jScrollPane1.setViewportView(jtFin);

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 903, Short.MAX_VALUE)
    );
    jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
    );

    jTabbedPane1.addTab("FIN", jPanel1);

    jtVit.setModel(vitTableModel);
    jtVit.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jScrollPane2.setViewportView(jtVit);

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
      jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 903, Short.MAX_VALUE)
    );
    jPanel2Layout.setVerticalGroup(
      jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
    );

    jTabbedPane1.addTab("VIT", jPanel2);

    javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
    jPanel4.setLayout(jPanel4Layout);
    jPanel4Layout.setHorizontalGroup(
      jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 0, Short.MAX_VALUE)
    );
    jPanel4Layout.setVerticalGroup(
      jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 120, Short.MAX_VALUE)
    );

    javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
      jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel3Layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jTabbedPane1))
      .addGroup(jPanel3Layout.createSequentialGroup()
        .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addContainerGap())
    );
    jPanel3Layout.setVerticalGroup(
      jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
        .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap())
    );

    jpBotoes.setLayout(new java.awt.BorderLayout(10, 10));

    jButton1.setText("Importar Arq. LOG");
    jButton1.setToolTipText("Importa o arquivo de log de venda \\n para o banco de dados");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });
    jpBotoes.add(jButton1, java.awt.BorderLayout.CENTER);

    jButton2.setText("Exportar Alter.");
    jpBotoes.add(jButton2, java.awt.BorderLayout.PAGE_START);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jpBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addComponent(jpBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
          .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {
      getLog(new FileReader("/home/camilo/log20150204.001"));
    } catch (FileNotFoundException ex) {
      Logger.getLogger(ImportaLogJDialog.class.getName()).log(Level.SEVERE, null, ex);
    }
  }//GEN-LAST:event_jButton1ActionPerformed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(ImportaLogJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    //</editor-fold>
    //</editor-fold>
    //</editor-fold>

    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        ImportaLogJDialog dialog = new ImportaLogJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton jButton1;
  private javax.swing.JButton jButton2;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JPanel jPanel2;
  private javax.swing.JPanel jPanel3;
  private javax.swing.JPanel jPanel4;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JScrollPane jScrollPane2;
  private javax.swing.JTabbedPane jTabbedPane1;
  private javax.swing.JPanel jpBotoes;
  private javax.swing.JTable jtFin;
  private javax.swing.JTable jtVit;
  // End of variables declaration//GEN-END:variables

//  
  private void getLog(FileReader file) {
    Scanner scanner = new Scanner(file);
    while (scanner.hasNext()) {
      String linhalog = scanner.nextLine();
      String[] arraylog = linhalog.split("\\|", -1);
      
      if (linhalog.startsWith("VIT")) {
        Vit v = new Vit();
        v.setOperador(linhalog.split("\\|")[1].split(":")[0]);
        v.setEstacao(linhalog.split("\\|")[1].split(":")[1]);
        v.setUnidade(linhalog.split("\\|")[2]);
        v.setCupom(linhalog.split("\\|")[3]);
        v.setCodBarras(linhalog.split("\\|")[6]);
        v.setDescricao(linhalog.split("\\|")[7]);

        lstvit.add(v);
      } else if (arraylog[0].startsWith("FIN")) {
        Fin f = new Fin();
        f.setOperador(arraylog[1].split(":")[0]);
        f.setEstacao(arraylog[1].split(":")[1]);
        f.setUnidade(arraylog[2]);
        f.setCupom(arraylog[3]);
        f.setEcf(arraylog[4]);
        f.setDataComputador(Util.parseDataSToD(arraylog[5].split(":")[0], "ddMMyykkmmss"));
        f.setDataEcf(Util.parseDataSToD(arraylog[5].split(":")[1], "ddMMyykkmmss"));
        f.setCodFinalizadora(arraylog[6]);
        f.setCodFinalizadoraPdv(arraylog[7]);

        String valor = arraylog[8];
        if (!valor.isEmpty()) {
          f.setValorPagamento(new BigDecimal(valor));
        } else {
          f.setValorPagamento(BigDecimal.ZERO);
        }

        f.setCodFinalizadoraTroco(arraylog[9]);

        valor = arraylog[10];
        if (!valor.isEmpty()) {
          f.setValorTroco(new BigDecimal(valor));
        } else {
          f.setValorTroco(BigDecimal.ZERO);
        }

        f.setDescricao(arraylog[11]);
        f.setAbreGaveta(arraylog[12]);
        f.setRegistro(arraylog[13]);
        f.setCodConvenio(arraylog[14]);
        f.setContCCF(arraylog[15]);
        f.setContGNF(arraylog[16]);
        f.setTransacao(arraylog[17]);
        f.setNumContSangria(arraylog[18]);
        f.setSupervSangria(arraylog[19]);
        f.setCpfCnpj(arraylog[21]);
        f.setBanco(arraylog[22]);
        f.setAgencia(arraylog[23]);
        f.setConta(arraylog[24]);
        f.setNumCheque(arraylog[25]);
        f.setTelefone(arraylog[26]);
        f.setDocumento(arraylog[27]);
        valor=arraylog[28];
        if(!valor.isEmpty()){
        f.setDataVencCheque(Util.parseDataSToD(valor, "ddMMyyyy"));
        }else{
        f.setDataVencCheque(null);
        }
        f.setLinhaChequeDig01(arraylog[29]);
        f.setCmc701(arraylog[30]);
        f.setCmc702(arraylog[31]);
        f.setCmc703(arraylog[32]);
        f.setCodLiberacao(arraylog[33]);

        valor = arraylog[34];
        if (!valor.isEmpty()) {
          f.setJurosCheque(new BigDecimal(valor));
        } else {
          f.setJurosCheque(BigDecimal.ZERO);
        }

        f.setTransacaoCartaoOnOff(Boolean.parseBoolean(arraylog[40]));
        f.setNumParcelas(arraylog[41]);
        f.setNumParcelasCDC(arraylog[42]);
        f.setSitef100ModPag(arraylog[43]);
        f.setSitef101ModPagTxtReal(arraylog[44]);
        f.setSitef102ModPagTxtDesc(arraylog[45]);
        f.setSitef120BuferCheque(arraylog[46]);
        f.setSitef123GrpImpresso(arraylog[47]);
        f.setSitef131Entidade(arraylog[48]);
        f.setSitef132TipoCartao(arraylog[49]);
        f.setSitef133NSUSitef(arraylog[50]);
        f.setSitef134NSUHost(arraylog[51]);
        f.setSitef135CodAut(arraylog[52]);
        f.setSitef136Bin(arraylog[53]);
        f.setSitef156Inst(arraylog[54]);
        f.setSitef157CodEst(arraylog[55]);
        f.setSitef158CodRedeAut(arraylog[56]);
        f.setSitef519CodPlano(arraylog[57]);
        f.setSitefNSU(arraylog[58]);
        f.setCodBinCentral(arraylog[70]);
        f.setCodCliente(arraylog[71]);
        f.setNomeCliente(arraylog[72]);
        f.setClasseCliente(arraylog[73]);
        f.setNumFabECF(arraylog[74]);

        lstfin.add(f);

      }
    }

    for (int i = 0; i < lstfin.size(); i++) {
      FinDaoHibernate findao = DaoFactory.criarFinDAO();
      findao.salvar(lstfin.get(i));
    }

    finTableModel.adicionaLista(lstfin);
    vitTableModel.adicionaLista(lstvit);
  }
}
